var $j = jQuery.noConflict();
$j(function() {
	
	$j('#container').layout({
		north: {
			resizable: false,
			minSize: 60
		}
	});

	$j( "#accordion" ).accordion({
		fillSpace: true,
		collapsible: true
	});
	
	var maintab = $j("#mainTab" ).tabs({
		tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>"
	});
	var tab_counter = 4;
	
	$j( "#mainTab span.ui-icon-close" ).live( "click", function() {
		var index = $j( "li", maintab ).index( $j( this ).parent() );
		maintab.tabs( "remove", index );
	});
	
	var $dialog = $j( "#dialog" ).dialog({
		autoOpen: false,
		modal: true,
		buttons: {
			Add: function() {
				var title = $j("#tab_title").val();
				var url = $j("#tab_content").val();
				addTab(title, url);
				$j(this).dialog( "close" );
			},
			Cancel: function() {
				$j(this).dialog( "close" );
			}
		},
		open: function() {
			$j("#tab_title").focus();
		},
		close: function() {
			$form[0].reset();
		}
	});
	
	$j("#add_tab").button().click(function() {
		$dialog.dialog( "open" );
	});
	
	var $form = $j("form", $dialog ).submit(function() {
		$dialog.dialog( "close" );
		return false;
	});
	
	function addTab(title, url) {
		var id = "mainTab-" + tab_counter;
		
		var mainTab_content = $j("#mainTab_content");
		
		var panel = $j("<div/>" ).attr({
	        "id": id,
	        "scrolling": "no",
	        "align" : "center",
	        "style": "padding: 0 0 0 0; margin: 0 0 0 0;"
	    })
	    .css({
	    	"align": 'center'
	    })
	    .appendTo(maintab);
		
		maintab.tabs( "add", "#" + id, title);
		
		maintab.tabs( "select" , id );
		var subIfr = $j("<iframe/>").attr({
	        "frameBorder": "0",
	        "scrolling": "no",
	        "allowTransparency": "true",
	        "src": url
	    }).css({
	    	"align": 'center',
	        "width": "100%",
	        "height": "100%"
	    }).load( function() {
	        var iframe = $j(this);
	        iframe.height($j("#mainTab").height()-65);
	    }).appendTo(panel);
		tab_counter++;
	}
	
	$j("#add_grid").button().click(function() {
		alert($j("#mainTab").height() + " || " + $j("#paddingWrapper").height());
	});
});
